<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
    </el-row>

    <el-table v-loading="loading" :data="requisitionlineList" @selection-change="handleSelectionChange" border>
      <el-table-column label="序号"  type="index" width="50"/>
      <el-table-column label="物料编码" align="center" prop="itemCode" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />

      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="库区" align="center" prop="locationName" />
      <el-table-column label="库位" align="center" prop="areaName" />
      <el-table-column label="单价（主）" align="center" prop="price" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
          v-for="col in columnsConfig"
          :key="col.prop"
          :label="col.label"
          :prop="col.prop"
          :width="col.width"
          :align="col.align"
          v-if="col.show">
      </el-table-column>

      <el-table-column label="单位（主）" align="center" prop="unitOfMeasure" fixed="right"/>
      <el-table-column label="领料数量（主）" align="center" prop="quantityIssued" fixed="right"/>
      <el-table-column label="单位（辅）" align="center" prop="storageUnit"  fixed="right"/>
      <el-table-column label="出库数量（辅）" align="center"   prop="storageUnitquantity" fixed="right">
        <template slot-scope="scope">
          <el-tag type="success" v-if="'Y' == scope.row.enableMultiUnit">{{ scope.row.storageUnitquantity }}</el-tag>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" v-if="optType == 'execute'" width="100px" fixed="right">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-if="optType != 'view'"
              v-hasPermi="['wm:issueother:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改返修领料单体对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="物料编码" prop="itemCode" readonly>
              <el-input v-model="form.itemCode" readonly="readonly" placeholder="请选择产品物料编码">
                <el-button slot="append" @click="handleSelectStock" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
            <StockSelect ref="stockSelect" @onSelected="onStockSelected"  ></StockSelect>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入物料名称" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" placeholder="请输入单位" readonly/>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="领料数量" prop="quantityIssued">
<!--              <el-input v-model="form.quantityIssued" placeholder="请输入领料数量" />-->
              <el-input-number :min=0 :step="1" v-model="form.quantityIssued" placeholder="请输入领料数量"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次号" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格型号" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouseName">
              <el-input v-model="form.warehouseName" placeholder="请输入仓库" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库区" prop="locationName">
              <el-input v-model="form.locationName" placeholder="请输入库区" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库位" prop="areaName">
              <el-input v-model="form.areaName" placeholder="请输入库位" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRequisitionline, getRequisitionline, delRequisitionline, addRequisitionline, updateRequisitionline } from "@/api/mes/rr/requisitionline";
import StockSelect from "@/components/stockSelect/single.vue";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";
import Template from "@/views/print/printtemplate/list.vue";

export default {
  name: "Requisitionline",
  components: {Template, StockSelect},
  props: {
    optType: null,
    orderId: null,

  },
  data() {
    return {
      columnsConfig:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 返修领料单体表格数据
      requisitionlineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId:this.orderId,
        itemCode: null,        itemName: null,      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemCode: [
          {required: true, message: "物料编码不能为空", trigger: "blur"}
        ],
        quantityIssued: [
          {required: true, message: "领料数量不能为空", trigger: "blur"},
          { validator: this.checkQuantity, trigger: 'blur' }
        ],
      }
    };
  },
  created() {
    console.log("createtttttt",this.requisitionlineList)
    this.getList();
    this.getItemBase()
  },
  methods: {
    checkQuantity(rule, value, callback) {
      if (value <= 0) {
        return callback(new Error('领料数量必须大于0'));
      }
      callback(); // 如果值大于0，则通过校验
    },
    /** 查询返修领料单体列表 */
    getList() {

      if(this.orderId){
        console.log("33333")
        this.loading = true;
        listRequisitionline(this.queryParams).then(response => {
          this.requisitionlineList = response.rows;
          this.total = response.total;
          this.loading = false;
          console.log('getlistggggggg',this.requisitionlineList)
        });
      }else{
        this.loading = false
      }
      this.$emit('change',this.requisitionlineList);
    },
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
      })
    },
    handleSelectStock() {
      this.$refs.stockSelect.showFlag = true;
      this.$refs.stockSelect.getList();
    },
    //物料选择弹出框
    onStockSelected(obj) {
      this.reset()
      if (obj != undefined && obj != null) {
        this.form.materialStockId = obj.materialStockId;
        this.form.itemId = obj.itemId;
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.specification = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
        this.form.batchCode = obj.batchCode;
        this.form.warehouseId = obj.warehouseId;
        this.form.warehouseCode = obj.warehouseCode;
        this.form.warehouseName = obj.warehouseName;
        this.form.locationId = obj.locationId;
        this.form.locationCode = obj.locationCode;
        this.form.locationName = obj.locationName;
        this.form.areaId = obj.areaId;
        this.form.areaCode = obj.areaCode;
        this.form.areaName = obj.areaName;
        this.$forceUpdate()
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        orderId: null,        materialStockId: null,        itemId: null,        itemCode: null,        itemName: null,        specification: null,        unitOfMeasure: null,        quantityIssued: null,        batchCode: null,        warehouseId: null,        warehouseCode: null,        warehouseName: null,        locationId: null,        locationCode: null,        locationName: null,        areaId: null,        areaCode: null,        areaName: null,        remark: null,        createBy: null,        createTime: null,        createByName: null,        updateBy: null,        updateTime: null,        tenantId: null      };
      this.resetForm("form");

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加返修领料单体";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // 直接使用当前行数据（不再调用API）
      this.form = {...row};  // 使用浅拷贝
      this.open = true;
      this.title = "修改返修领料";
  /*    const id = row.id || this.ids
      getRequisitionline(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改返修领料单体";
      });*/
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 新增：判断是新增还是修改操作
          if (this.form.id) {
            // 修改现有行
            const index = this.requisitionlineList.findIndex(tableitem => tableitem.id === this.form.id);
            if (index !== -1) {
              this.requisitionlineList.splice(index, 1, {...this.form});
            }
          } else {
            // 新增行
            // 添加orderId关联
            this.form.orderId = this.orderId;
            this.requisitionlineList.push({...this.form});
          }

          this.open = false;
          // 触发事件通知父组件
          this.$emit('change',this.requisitionlineList);

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
/* 父类单据头 确定后才执行删除
// 删除时  已有ID的行通过ID删除 五id直接找到对象删除
      if (row.id) {
        // 已有ID的行通过ID删除
        const index = this.requisitionlineList.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.requisitionlineList.splice(index, 1);
        }
      } else {
        // 新增的删除
        const index = this.requisitionlineList.indexOf(row);
        if (index !== -1) {
          this.requisitionlineList.splice(index, 1);
        }
      }
      // 重置选中状态
      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.$emit('change', this.requisitionlineList);
      */

      this.$modal.confirm('是否确认删除该物料的数据项？').then(function() {
        return delRequisitionline(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rr/requisitionline/export', {
        ...this.queryParams
      }, `requisitionline_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
